<template>
  <el-tabs v-model="activeName" type="border-card" class="as-card custom-table">
    <el-tab-pane label="最新资源" name="files" style="max-height: 24rem; overflow-y: auto;">
      <item
        v-for="item in items['files']"
        :key="item.id"
        type="files"
        :item="item"
        class="easy-container"
        :class="{ 'm-r-10': items['files'].length > 5 }"
      />
      <load-more :next-page="nextPage['files']" :loading="loading" @loadMore="loadRecentItems" />
    </el-tab-pane>
    <el-tab-pane label="最新问题" name="issues" style="max-height: 24rem; overflow-y: auto;">
      <item
        v-for="item in items['issues']"
        :key="item.id"
        type="issues"
        :item="item"
        class="easy-container"
        :class="{ 'm-r-10': items['files'].length > 5 }"
      />
      <load-more :next-page="nextPage['issues']" :loading="loading" @loadMore="loadRecentItems" />
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import Item from '@/views/groups/show/activities/components/activities-ranking-item';
import LoadMore from '@/components/load-more';
import { formatRanking } from '@/views/groups/format';

export default {
  name: 'recent-items',
  components: { Item, LoadMore },
  data() {
    return {
      activeName: 'files', // 写成后端的样子就懒得再转了
      loading: false,
      items: {
        files: [],
        issues: [],
      },
      nextPage: {
        files: null,
        issues: null,
      },
    };
  },
  computed: {
    loadRecentItemsParams() {
      return {
        groupId: this.$route.params.groupId,
        type: this.activeName,
        number: 5,
      };
    },
  },
  created() { this.loadRecentItems(); },
  methods: {
    loadRecentItems(page = 1) {
      if (this.items[this.activeName].length && page === 1) return; // 重复不再请求
      this.loading = true;
      const params = Object.assign({}, this.loadRecentItemsParams, { page });
      this.$api.groups.recentItems(params)
        .then((res) => {
          const oldItems = this.items[this.activeName];
          Object.assign(this.items, {
            [this.activeName]: oldItems.concat(formatRanking(this.activeName, res.data)),
          });
          Object.assign(this.nextPage, {
            [this.activeName]: res.kaminari.next_page,
          });
        })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
  },
  watch: {
    loadRecentItemsParams() { this.loadRecentItems(); },
  },
};
</script>

<style></style>
